/**
 * 
 */
package com.qq.spirit;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.gargoylesoftware.htmlunit.util.NameValuePair;
import com.qq.jutil.util.Pair;
import com.qq.spirit.inter.AbstractActionAfterHttpRequest;
import com.qq.spirit.inter.TaskUnit;
import com.qq.spirit.model.UserData;
import com.qq.spirit.model.XmlDataUtil;
import com.qq.spirit.model.XmlNodeData;

/**
 * 通商任务
 * 
 * @author beedoorwei
 * 
 */
public class CaravanTask extends TaskUnit
{
	public CaravanTask()
	{
		this.username = "通商任务";
	}

	@Override
	public void doTask()
	{
		try
		{
			Iterator<String> ite = UserCache.userQueue.keySet().iterator();
			while (ite.hasNext())
			{
				String username = ite.next();
				TaskManager.addTask(new Caravan(username), GameUtil.randomInt(10));
			}
		} catch (Exception e)
		{
			LoggerUtil.error(e);
		}
	}

	/**
	 * 通商任务
	 * 
	 * @author Administrator
	 * 
	 */
	class Caravan extends TaskUnit
	{
		public Caravan(String username)
		{
			this.username = username;
		}

		public void doTask()
		{
			try
			{
				UserData u = UserCache.get(username);
				if (u.getUserState() == UserState.LOGIN_GAME)
				{
					HttpUtil.doGet(username, GameConstants.CARAVAN_QUERY_URL, new CaravanInfo(username));
				} else
				{
					// 添加登录任务先
					TaskManager.addTask(new LoginTask(username, new Caravan(username)));
				}
			} catch (Exception e)
			{
				LoggerUtil.error(e);
			}
		}
	}

	/**
	 * 通商前查询
	 * 
	 * @author Administrator
	 * 
	 */
	class CaravanInfo extends AbstractActionAfterHttpRequest
	{
		public CaravanInfo(String username)
		{
			super();
			this.username = username;
			this.taskUnit = new Caravan(username);
		}

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * com.qq.spirit.inter.AbstractActionAfterHttpRequest#doCall(java.util
		 * .List, com.qq.spirit.model.XmlNodeData)
		 */
		@Override
		public void doCall(List<NameValuePair> headerList, XmlNodeData CaravanInfo)
		{
			String s = XmlDataUtil.getNodeData(CaravanInfo, "results.tradetimes");
			if (GameUtil.convertInt(s) > 0)
			{
				List<XmlNodeData> tradecombodtoStr = XmlDataUtil.getNodeInfoList(CaravanInfo, "results.tradecombodto.info");
				// 目前默认低优先级事件优先
				List<XmlNodeData> refreshStr = XmlDataUtil.getNodeInfoList(CaravanInfo, "results.refresh.name");
				List<XmlNodeData> recentStr = XmlDataUtil.getNodeInfoList(CaravanInfo, "results.recent.name");

				// 找到了最优的
				int caravanId = getCaravanId(refreshStr, tradecombodtoStr, recentStr);

			}
		}

		/**
		 * 寻找通商队伍
		 * 
		 * @param refreshStr
		 * @param tradecombodtoStr
		 * @param recentStr
		 * @return
		 */
		private int getCaravanId(List<XmlNodeData> refreshStr, List<XmlNodeData> tradecombodtoStr, List<XmlNodeData> recentStr)
		{
			List<Pair<Integer, String>> tradecombodtoList = new ArrayList<Pair<Integer, String>>();
			if (!recentStr.isEmpty())
			{
				for (XmlNodeData x : tradecombodtoStr)
				{
					String type = XmlDataUtil.getNodeData(x.getParent(), "type");
					String event = x.getNodeValue();
					String[] evArray = event.split(",");
					List<String> lList = new ArrayList<String>();
					List<String> rList = new ArrayList<String>();
					if (evArray.length == 2)
					{
						if (!evArray[0].equals(""))
						{
							String[] s2 = evArray[0].split("[+]");
							for (String s1 : s2)
							{
								lList.add(s1);
							}
							searchMatcher(tradecombodtoList, Pair.makePair(type, lList), recentStr, 0);
						}
						if (!evArray[1].equals(""))
						{
							String[] s2 = evArray[1].split("[+]");
							for (String s1 : s2)
							{
								rList.add(s1);
							}
							searchMatcher(tradecombodtoList, Pair.makePair(type, rList), recentStr, 0);
						}

						LoggerUtil.info("已完成通商事件：" + type + ":" + Arrays.toString(rList.toArray()));
						LoggerUtil.info("已完成通商事件：" + type + ":" + Arrays.toString(lList.toArray()));
					}

				}
			}

			List<Pair<Integer, String>> doData = new ArrayList<Pair<Integer, String>>();
			if (!tradecombodtoList.isEmpty())
			{
				// 以银币优先，低优先级事件优先为原则，进行查找
				for (Pair<Integer, String> x : tradecombodtoList)
				{
					for (XmlNodeData r : refreshStr)
					{
						if (r.getNodeValue().equals(x.second))
						{
							doData.add(x);
						}
					}
				}
			}

			String mName = "";
			if (doData.isEmpty())
			{
				XmlNodeData t = null;
				for (XmlNodeData r : refreshStr)
				{
					if (t == null)
					{
						t = r;
					} else
					{
						if (GameConstants.caravanEventMap.get(t.getNodeValue()) <= GameConstants.caravanEventMap.get(r.getNodeValue()))
						{
							// t的权重小于r的权重，采用r
							t = r;
						}
					}
				}
				mName = t.getNodeValue();
			} else
			{
				Pair<Integer, String> t = null;
				for (Pair<Integer, String> x : doData)
				{
					if (t == null)
					{
						t = x;
					} else
					{
						if (GameConstants.caravanEventMap.get(t.second) <= GameConstants.caravanEventMap.get(x.second))
						{
							// t的权重小于r的权重，采用r
							t = x;
						}
					}
				}
				mName = t.second;
			}

			// 找到了最优化的
			String ss = "";
			for (XmlNodeData x : refreshStr)
			{
				// 待通商
				ss += x.getNodeValue() + ",";
			}
			LoggerUtil.info("待通商队伍 " + ss);

			ss = "";
			for (XmlNodeData x : recentStr)
			{
				// 待通商
				ss += x.getNodeValue() + ",";
			}
			LoggerUtil.info("已通商商队伍 " + ss);

			return GameConstants.caravanEventMap.get(mName);
		}

		/**
		 * 递归查找
		 * 
		 * @param rList
		 * @param event
		 * @param recentStr
		 * @param idx
		 */
		private void searchMatcher(List<Pair<Integer, String>> tradecombodtoList, Pair<String, List<String>> event, List<XmlNodeData> recentStr, int idx)
		{
			if (recentStr.isEmpty())
			{
				return;
			}
			if (event.second.isEmpty())
			{
				return;
			}
			// 因为最多只会有4个商人组合的触发事件
			boolean flag = false;
			for (int i = 0; i <= idx && i < recentStr.size(); i++)
			{
				String re = recentStr.get(recentStr.size() - i - 1).getNodeValue();
				if (!event.second.get(idx).equals(re))
				{
					flag = true;
					break;
				}
			}
			if (!flag)
			{
				if (event.second.size() > idx + 1)
				{
					Pair<Integer, String> dPair = Pair.makePair(GameUtil.convertInt(event.first), event.second.get(idx + 1));
					tradecombodtoList.add(dPair);
					searchMatcher(tradecombodtoList, event, recentStr, idx + 1);
				}
			}
		}
	}
}